package org.amos.filestorage.platform.local;

import cn.hutool.core.io.FileUtil;
import org.amos.core.basic.constant.SystemConstant;
import org.amos.filestorage.exception.FileStorageException;
import org.amos.filestorage.platform.AbstractFilePlatform;
import org.amos.filestorage.platform.config.LocalFilePlatformConfig;
import org.junit.internal.Throwables;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.function.Consumer;

/**
 * 本地文件存储
 */
public class LocalFilePlatform extends AbstractFilePlatform<LocalFilePlatformConfig> {

    public LocalFilePlatform(String id, LocalFilePlatformConfig config) {
        super(id, config);
    }

    @Override
    protected void initClient() {

    }

    @Override
    public String upload(byte[] bytes, String path, String type) {
        String absolutePath = getAbsolutePath(path);
        FileUtil.writeBytes(bytes, absolutePath);
        return config.getDomain() + SystemConstant.SYS_LOCAL_FILE_PATH + path;
    }

    @Override
    public Boolean delete(String path) {
        return FileUtil.del(getAbsolutePath(path));
    }


    @Override
    public Boolean exists(String path) {
        return new File(getAbsolutePath(path)).exists();
    }

    @Override
    public void download(String path, Consumer<InputStream> consumer) {
        try (InputStream in = FileUtil.getInputStream(getAbsolutePath(path))) {
            consumer.accept(in);
        } catch (IOException e) {
            throw new FileStorageException(Throwables.getStacktrace(e));
        }
    }

    /**
     * 获取本地绝对路径
     */
    public String getAbsolutePath(String path) {
        return config.getBasePath() + path;
    }
}
